package com.inkyi.assistant.app.tools;

import com.inkyi.assistant.app.base.InkComponent;
import com.inkyi.assistant.app.tools.base.InkTools;
import com.inkyi.assistant.app.tools.base.InkToolsCellRenderer;
import com.inkyi.assistant.app.tools.base.InkToolsListModel;
import com.inkyi.assistant.app.tools.comps.*;
import com.inkyi.framework.daqian.gui.InkGuiHelper;
import com.inkyi.framework.daqian.gui.core.Workspace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.util.Objects;

public class ToolListingsPanel extends JPanel implements InkComponent {

    private static Logger logger = LoggerFactory.getLogger(ToolListingsPanel.class);

    private JList<InkTools> toolList;

    private InkToolsListModel listModel;

    private JScrollPane scrollPane;

    public ToolListingsPanel() {
        initComponents();
    }

    @Override
    public void initComponents() {
        setLayout(new CardLayout());
        toolList = new JList<>();
        toolList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        toolList.setCellRenderer(new InkToolsCellRenderer());
        listModel = new InkToolsListModel();
        toolList.setModel(listModel);

        toolList.addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                InkTools selectedItem = toolList.getSelectedValue();
                if (Objects.equals("workspace", selectedItem.getOpenType())) {
                    Workspace workspace = InkGuiHelper.getWorkspace();
                    String toolId = selectedItem.getToolID();
                    if (!workspace.existTabComp(toolId)) {
                        workspace.addTabComp(selectedItem.getToolID(), selectedItem.getToolName(), selectedItem.getComponent());
                    }
                    workspace.openTabComp(toolId);
                } else if (Objects.equals("JFrame", selectedItem.getOpenType())) {
                    JFrame frame = new JFrame();
                    frame.setTitle(selectedItem.getToolName());
                    frame.setSize(1000, 800);
                    frame.setContentPane(selectedItem.getComponent());
                    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                    frame.pack();
                    frame.setVisible(true);
                }
            }
        });

        listModel.addTools(new EnvironmentVarTool());
        listModel.addTools(new NovaGeneralPwdTool());
        listModel.addTools(new NetworkTool());
        listModel.addTools(new JsonViewTool());
        listModel.addTools(new TodoListTool());

        scrollPane = new JScrollPane(toolList);
        add(scrollPane);
    }
}
